package com.vcredit.creditcat.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.vcredit.creditcat.framework.pagination.DefaultCriteria;
import com.vcredit.creditcat.framework.pagination.Page;
import com.vcredit.creditcat.model.RoleResource;
import com.vcredit.creditcat.persistence.RoleResourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;

import com.vcredit.creditcat.model.Resource;
import com.vcredit.creditcat.model.Role;
import com.vcredit.creditcat.persistence.ResourceMapper;
import com.vcredit.creditcat.persistence.RoleMapper;

/**
 * 角色业务类
 *
 */
@Service
public class RoleService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private ResourceMapper resourceMapper;

	@Autowired
	private RoleResourceMapper roleResourceMapper;

	public Page<Role> findByPage(DefaultCriteria criteria){
		long count=roleMapper.findByPageCount(criteria);
		List<Role> roleList=roleMapper.findByPage(criteria);
		return new Page(count, roleList);
	}
	public void insert(Role role){
		roleMapper.insert(role);
	}

	public List<Role> findByUserId(Long userId){
		return roleMapper.findByUserId(userId);
	}

	public List<Role> findChannelRoles(){
		return roleMapper.findChannelRoles();
	}
	public List<Role> findAll(){
		List<Role> roleList=roleMapper.findAll();
		return roleList;
	}
	public void insertRoleResource(RoleResource roleResource){
		roleResourceMapper.insert(roleResource);
	}

	/**
	 * 返回资源权限集合
	 * 
	 * @return
	 */
	public Map<String, Collection<ConfigAttribute>> getResourceMap() {
		Map<String, Collection<ConfigAttribute>> resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		List<Resource> resources = resourceMapper.findAll();
		for (Resource resource : resources) {
			if (resource.getValue() != null && !"".equals(resource.getValue())) {
				Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
				List<Role> roles = roleMapper.findByResourceId(resource.getId());
				for (Role role : roles) {
					ConfigAttribute c = new SecurityConfig(role.getRoleName());
					atts.add(c);
				}
				resourceMap.put(resource.getValue(), atts);
			}
		}
		return resourceMap;
	}

}
